package com.imon.jmxbox;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

@Component
public class FrontDeskImpl implements FrontDesk {

	private static Log LOG = LogFactory.getLog(FrontDeskImpl.class);

	@Resource
	private ConnectionFactory connectionFactory;

	@Resource
	private Destination destination;

	public void sendMail(Mail aMail) {
		LOG.debug("Sending mail from FrontDesk");

		Connection conn = null;

		try {
			conn = connectionFactory.createConnection();
			Session session = conn.createSession(false,
					Session.AUTO_ACKNOWLEDGE);

			MessageProducer producer = session.createProducer(destination);

			MapMessage message = session.createMapMessage();
			message.setString("mailId", aMail.getMailId());
			message.setString("country", aMail.getCountry());
			message.setDouble("weight", aMail.getWeight());

			producer.send(message);

			session.close();
		} catch (JMSException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (JMSException e) {
					LOG.error(e);
				}
			}
		}
	}
}
